<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>分享</title>
        <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
        <link rel="stylesheet" href="https://static.91haoka.cn/vant.css"/>
        <script src="https://static.91haoka.cn/vue.min.js"></script>
        <script src="https://static.91haoka.cn/vantall.js"></script>
        <script src="https://static.91haoka.cn/axios.min.js"></script>
		<link rel="stylesheet" type="text/css" href="https://static.91haoka.cn/all.css"/>
		<script src="js/q.js"></script>
		<script src="js/fuzhi.js"></script>
     </head>
    <style type="text/css">
		*{ box-sizing: border-box; font-family:'PingFang SC';}
		
    </style>
	<body>
        <div id="app" style="min-height: 100vh; background: rgb(243, 243, 245); padding-top: 0.2rem;" v-cloak>
			
			<div style="margin: 0.2rem; padding: 0.4rem; background: #fff; border-radius: 0.2rem; background: #fff;">
				
				
				<div>
					<img :src="img" style="max-width: 100%;">
				</div>
				<div style="margin: 20px 0;">
					<div style="width: 200px; height: 200px; margin: 0 auto;">
						<div id="qrcode" ref="qrcode"></div>
					</div>
					<!-- <div style=" color: rgb(0, 124, 255); text-align: center; font-size: 14px; margin-top: 30px;" @click="baocun">保存二维码</div> -->
				</div>
				<div style="margin-bottom: 20px; font-size: 14px; text-align: center;">
					长按识别二维码
					
				</div>
				<!-- <div class="flexbc" style="padding:0 0  0.4rem;">
					<div style="font-size: 0.28rem; width: 5rem;">商品连接：{{url2}}</div>
					<div style="color: rgb(0, 124, 255); font-size: 0.28rem;" @click=fuzhi(url2)>复制</div>
				</div> -->
				
			</div>
			<div style="position: fixed; bottom: 1rem; left: 0; width: 100%;" class="flexcc">
				<div class="flexcc" @click="fuzhi(url2)" style="background: rgb(255, 28, 59); color: #fff; font-size: 0.32rem; margin: 0 0.2rem; padding: 0 0.3rem; height: 0.8rem; border-radius: 0.4rem;">复制链接</div>
				<div class="flexcc" @click="haibao" style="background: rgb(255, 28, 59); color: #fff; font-size: 0.32rem; margin: 0 0.2rem; padding: 0 0.3rem; height: 0.8rem; border-radius: 0.4rem;">分享海报</div>
			</div>
			
			<!-- <canvas id="myCanvas" width="750" style="background: #fff;"></canvas> -->
			
			<van-popup v-model="fenxiangtulog" style="width: 90%; background: #fff !important;">
				<img :src="img3" style="width: 100%;">
			</van-popup>
        </div>

       
        <script>
            var h = document.documentElement.clientWidth / 7.5 + 'px';
                document.documentElement.style.fontSize = h;

            
            new Vue({
                el: '#app',
                data: function() {
                	return {
                       url2:"",
					   img:"",
					   img2:"",
					   img3:"",
					   fenxiangtulog:false,
					   msg:"",
					   apis:""
                	}
                },
                created(){
						
						if (location.href.includes('localhost')) {
							this.apis = '/apis'
						}
                },
                mounted () {
					
				
					this.url2 = "http://storep.91haoka.cn/h5/dingdan.html?id="+this.getUrlParam('id')
					
					axios.get(`${this.apis}/api/page/info?id=${this.getUrlParam('id')}`)
						.then(response => {
							if(response.data.data != '' && response.data.data){
								this.img = response.data.data.details
							}else{
								vant.Toast(response.data.msg.info);
							}
						})
						
					var qrcode = new QRCode(document.getElementById('qrcode'), {
					    text: this.url2,
					    width: 200,
					    height: 200,
					    colorDark : "#000000",
					    colorLight : "#ffffff",
					    correctLevel : QRCode.CorrectLevel.H
					})
					
					
					
					setTimeout(()=>{
						var canvas = document.getElementById("qrcode").getElementsByTagName("canvas")[0];
						var img = canvas.toDataURL("image/png");
						
						function base64ImgtoFile (dataurl, filename = 'file') {
						        //将base64格式分割：['data:image/png;base64','XXXX']
						        const arr = dataurl.split(',')
						        // .*？ 表示匹配任意字符到下一个符合条件的字符 刚好匹配到：
						        // image/png
						        const mime = arr[0].match(/:(.*?);/)[1]  //image/png
						        //[image,png] 获取图片类型后缀
						        const suffix = mime.split('/')[1] //png
						        const bstr = atob(arr[1])   //atob() 方法用于解码使用 base-64 编码的字符串
						        let n = bstr.length
						        const u8arr = new Uint8Array(n)
						        while (n--) {
						            u8arr[n] = bstr.charCodeAt(n)
						        }
						        return new File([u8arr], `${filename}.${suffix}`, {
						            type: mime
						        })
						}
						
						const blob = base64ImgtoFile(img)
						
						axios.post(`${this.apis}/api/qiniu/token`,{bucket:"gth"})
							.then(response => {
							var qiniudata = new FormData();
								qiniudata.append('file', blob);
								qiniudata.append('token',response.data.data);
								
								axios.post('https://upload.qiniup.com',qiniudata)
									.then(response => {
										this.img2 = 'https://pic.91haoka.cn/' + response.data.key
									})
						})
						
				
						  
	// 					this.img2 = document.getElementById('qrcode').getElementsByTagName('img')[0];
	
	// 					this.msg = JSON.stringify(document.getElementById('qrcode').getElementsByTagName('img')[0]) 
					},1000)

					
				},
                methods:{
					haibao:function(){
						
						var that = this
						// var canvas = document.getElementById('myCanvas');
						var canvas = document.createElement('canvas')
						canvas.width = 750
						canvas.height = 300
						var ctx = canvas.getContext('2d');
						var canvas_h = 0
						var img = new Image();
						// img.src = this.img2.currentSrc  // 图像路径
						let p = new Promise((res,rej)=>{
							if(this.img){
								img.src = this.img
								img.setAttribute("crossOrigin",'Anonymous')
								img.onload = function() {
									let img_w = 750
									let bili = 750 / img.width 
									let img_h = parseInt(img.height * bili)
									canvas_h = img_h
									canvas.setAttribute("height", canvas_h + 300);
									ctx.drawImage(img,0,0,img_w,img_h);  // 将图像绘制到Canvas上
									res('ok')
								};
								img.onerror = function(err){
									// that.msg = JSON.stringify(err)
								}
							}else{
								res('ok')
							}
							
							
						})
						p.then(()=>{
							var img2 = new Image();
							img2.src = this.img2
							img2.setAttribute("crossOrigin",'Anonymous')
							img2.onload = function() {
								ctx.drawImage(img2,275,canvas_h+20,200,200);  // 将图像绘制到Canvas上
								ctx.textAlign = "center";
								ctx.fillStyle = '#000';
								ctx.font = "30px serif";
								ctx.fillText('长按识别二维码', 375, canvas_h+260)
								
								var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
								for(var i = 0; i < imageData.data.length; i += 4) {
									if(imageData.data[i + 3] == 0) {
										imageData.data[i] = 255;
										imageData.data[i + 1] = 255;
										imageData.data[i + 2] = 255;
										imageData.data[i + 3] = 255;
									}
								}
								ctx.putImageData(imageData, 0, 0);
								
								var url = canvas.toDataURL('image/png');
								that.img3 = url
								that.fenxiangtulog = true
								
								var addElement = document.createElement('a')
								addElement.href = url
								addElement.download = "海报.png"
								document.body.appendChild(addElement)
								addElement.click();
								document.body.removeChild(addElement);
							}
							
							
							// const blobUrl = window.URL.createObjectURL(blob);
							// img2.src = blobUrl //转换成blob
							
							// // that.msg = blobUrl
							
							// // img2.src = that.img2.currentSrc //直接base64
							// img2.setAttribute("crossOrigin",'Anonymous')
							// img2.onload = function() {
								
							// 	ctx.drawImage(img2,275,canvas_h+20,200,200);  // 将图像绘制到Canvas上
							// 	ctx.textAlign = "center";
							// 	ctx.fillStyle = '#000';
							// 	ctx.font = "30px serif";
							// 	ctx.fillText('长按识别二维码', 375, canvas_h+260)
								
							// 	var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
							// 	for(var i = 0; i < imageData.data.length; i += 4) {
							// 		if(imageData.data[i + 3] == 0) {
							// 			imageData.data[i] = 255;
							// 			imageData.data[i + 1] = 255;
							// 			imageData.data[i + 2] = 255;
							// 			imageData.data[i + 3] = 255;
							// 		}
							// 	}
							// 	ctx.putImageData(imageData, 0, 0);
								
							// 	var url = canvas.toDataURL('image/png');
							// 	that.img3 = url
							// 	that.fenxiangtulog = true
								
							// 	var addElement = document.createElement('a')
							// 	addElement.href = url
							// 	addElement.download = "海报.png"
							// 	document.body.appendChild(addElement)
							// 	addElement.click();
							// 	document.body.removeChild(addElement);
							// }
							
							
							
							
						})
					},
					fuzhi:function(text){
						const clipboardData = window.clipboardData;
						if (clipboardData) {
						  clipboardData.clearData();
						  clipboardData.setData("Text", text);
						  return true;
						} else if (document.execCommand) {
						  const el = document.createElement("textarea");
						  el.value = text;
						  el.setAttribute("readonly", "");
						  el.style.position = "absolute";
						  el.style.left = "-9999px";
						  document.body.appendChild(el);
						  el.select();
						  document.execCommand("copy");
						  document.body.removeChild(el);
						  vant.Toast('已复制');
						  return true;
						}
						return false;
					},
					
					getUrlParam:function(name) {
					    var query = window.location.search.substring(1);
					    var vars = query.split("&");
					    for (var i=0;i<vars.length;i++) {
					            var pair = vars[i].split("=");
					            if(pair[0] == name){return pair[1];}
					    }
					    return(false);
					},
					baocun() {
							// 先找到canvas节点下的二维码图片
							const myCanvas = document.getElementById('qrcode').getElementsByTagName('canvas')
							const img = document.getElementById('qrcode').getElementsByTagName('img')
							// 创建一个a节点
							const a = document.createElement('a')
							// 设置a的href属性将canvas变成png格式
							const imgURL = myCanvas[0].toDataURL('image/jpg')
							const ua = navigator.userAgent
							if (ua.indexOf('Trident') !== -1 && ua.indexOf('Windows') !== -1) { // IE内核 并且  windows系统 情况下 才执行;
								var bstr = atob(imgURL.split(',')[1])
								var n = bstr.length
								var u8arr = new Uint8Array(n)
								while (n--) {
									u8arr[n] = bstr.charCodeAt(n)
								}
								const blob = new Blob([u8arr])
								window.navigator.msSaveOrOpenBlob(blob, '下载' + '.' + 'png')
							} else if (ua.indexOf('Firefox') > -1) { // 火狐兼容下载
								const blob = this.base64ToBlob(imgURL); //new Blob([content]);
								const evt = document.createEvent("HTMLEvents");
								evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
								a.download = ' '; //下载图片名称，如果填内容识别不到，下载为未知文件，所以我这里就不填为空
								a.href = URL.createObjectURL(blob);
								a.dispatchEvent(new MouseEvent('click', {
									bubbles: true,
									cancelable: true,
									view: window
								}));
							} else { // 谷歌兼容下载
								img.src = myCanvas[0].toDataURL('image/jpg')
								a.href = img.src
								// 设置下载文件的名字
								a.download = '下单页二维码';
								// 点击
								a.click();
								vant.Toast('已保存');
							}
						},
			 
						// base64转blob
						base64ToBlob(code) {
							let parts = code.split(';base64,');
							let contentType = parts[0].split(':')[1];
							let raw = window.atob(parts[1]);
							let rawLength = raw.length;
							let uInt8Array = new Uint8Array(rawLength);
							for (let i = 0; i < rawLength; ++i) {
								uInt8Array[i] = raw.charCodeAt(i);
							}
							return new Blob([uInt8Array], {
								type: contentType
							});
						}
                }
            });

  
        </script>
	</body>
</html>
